package cc.eddic.practice.spring.webapi;


import cc.eddic.practice.spring.domain.SubCategory;
import cc.eddic.practice.spring.dto.*;
import cc.eddic.practice.spring.repository.CategoryRepository;
import cc.eddic.practice.spring.repository.ExamRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.transaction.Transactional;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/categorys")
public class CategoryRestController {
    public CategoryRestController(CategoryRepository repository) {
        this.repository = repository;
    }


    @PostMapping
    public HttpEntity<?> add(@RequestBody final CategoryAddRequest model) {
        val category = repository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest
                ().path("/{id}").buildAndExpand(category.getId()).toUri()).build();
    }


    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id) {
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }


    @GetMapping("/{id}")
    public HttpEntity<CategoryResponse> get(@PathVariable("id") final long id) {
        if (log.isInfoEnabled()) log.info("id = {}", id);
        val category = repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(CategoryResponse.from(category));
    }

    @Transactional
    @PostMapping("/{categoryId}/subCategories")
    public HttpEntity<?> add(@PathVariable("categoryId") Long categoryId, @RequestBody final SubCategoryAddRequest model) {
        val category = repository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subCategory = model.as();
        category.add(subCategory);
        repository.save(category);

        val id =category.getSubCategories().stream()
                .filter(x -> x.getName().equals(model.getName()))
                .sorted(Comparator.comparing(SubCategory::getCreatedOn).reversed())
                .map(SubCategory::getId)
                .findFirst().orElse(-1L);
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{categoryId}/subCategories/{subcategoryId}").buildAndExpand(category.getId(),id).toUri()).build();
    }

    @GetMapping("/{categoryId}/subCategories")
    public HttpEntity<?> get(@PathVariable("categoryId") Long categoryId) {
        val category = repository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(category.getSubCategories().stream().map(SubCategoryResponse::from).collect(Collectors.toList()));
    }

    @GetMapping("/{categoryId}/subCategories/{subCategoryId}")
    public HttpEntity<?> get(@PathVariable("categoryId") Long categoryId, @PathVariable("subCategoryId") Long subCategoryId) {
        val category = repository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subCategory = category.getSubCategories().stream().filter(subcategory -> subcategory.getId().equals(subCategoryId)).findFirst().orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(SubCategoryResponse.from(subCategory));
    }

    @GetMapping
    public HttpEntity<List<CategoryResponse>> getAll() {
        return null;
    }

    private final CategoryRepository repository;
}
